package com.shyroke.daydayzhuanapi.mapper;

import cn.hutool.core.date.DateUtil;
import com.shyroke.daydayzhuanapi.dto.SubmitArt;
import com.shyroke.daydayzhuanapi.dto.SubmitArtAdminDto;
import com.shyroke.daydayzhuanapi.dto.SubmitArtDto;
import com.shyroke.daydayzhuanapi.entity.SubmitArtEntity;
import com.shyroke.daydayzhuanapi.entity.UserEntity;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class SubmitArtMapper {
    @Autowired
    private ModelMapper modelMapper;

    public SubmitArtDto entityToDto(SubmitArtEntity e) {
        SubmitArtDto dto = modelMapper.map(e, SubmitArtDto.class);
        dto.setShowCreateTime(DateUtil.format(e.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
        dto.setAuthor(e.getUser().getAuthor());
        return dto;
    }

    public SubmitArtAdminDto entityToAdminDto(SubmitArtEntity e) {
        SubmitArtAdminDto dto = modelMapper.map(e, SubmitArtAdminDto.class);
        dto.setShowCreateTime(DateUtil.format(e.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
        UserEntity user = e.getUser();
        dto.setPay(user.getPay());
        dto.setAuthor(user.getAuthor());
        return dto;
    }

    public SubmitArtEntity dtoToEntity(SubmitArt project,Integer uid) {
        SubmitArtEntity entity = modelMapper.map(project, SubmitArtEntity.class);
        Date currenDate = new Date();
        entity.setCreateTime(currenDate); //设置创建时间
        entity.setUpdateTime(currenDate);
        entity.setIsCheck(0);
        UserEntity user = new UserEntity();
        user.setId(uid);
        entity.setUser(user);
        Document document = Jsoup.parse(project.getContent());
        Elements elements = document.select("img");
        if(elements!=null&&elements.size()>0){
            for(int i= 0;i<elements.size();i++){
                Element element = elements.get(i);
                element.attr("alt",entity.getTitle()+"  第"+(i+1)+"张");
            }
            entity.setContent(document.html());
        }
        return entity;
    }
}
